package com.star.security.context;

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseCookie;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 返回权限令牌
 *
 * @author yangzj
 */
@AllArgsConstructor
@Getter
@Setter
public class ResponseToken {
    /**
     * 访问令牌
     */
    @JsonProperty("access_token")
    private String accessToken;

    /**
     * 有效时间（秒）
     */
    @JsonProperty("expires_in")
    private Long expiresIn;

    /**
     * 设置cookie
     *
     * @param response 回答
     */
    public void setCookie(HttpServletResponse response) {
        // 设置cookie
        ResponseCookie cookie = ResponseCookie.from(TokenRepository.TOKEN, accessToken)
                .httpOnly(true)
                .maxAge(expiresIn)
                .secure(true)
                .sameSite("Strict")
                .build();
        response.setHeader(HttpHeaders.SET_COOKIE, cookie.toString());
    }

    /**
     * 删除cookie
     *
     * @param request  请求
     * @param response 响应
     */
    public static void removeCookie(HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        if (cookies == null) {
            return;
        }
        for (Cookie c : cookies) {
            if (TokenRepository.TOKEN.equals(c.getName())) {
                Cookie cookie = new Cookie(TokenRepository.TOKEN, null);
                cookie.setMaxAge(0);
                response.addCookie(cookie);
            }
        }
    }

}
